#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>

#define MAXPENDING 5    /* Max connection requests */
#define BUFFSIZE 256

void Die(char *mess) { perror(mess); exit(1); }

int getArray(char a[], int size, char fileName[])
{
	printf ("\nFilename: %s", fileName);
        FILE *fp;
        fp = fopen(fileName, "r");      //open file , read only

        int i = 0;                      //array pointer run bt 0 - (size-1)
        char value;                      //keep value at pointer position

        /* loop until all data keep into array */
        while( (!feof(fp)) && (i < size))
	{
                fscanf(fp, "%c", &value);
                a[i] = value;
                i++;
        }
	a[i] = '\0';
	printf ("File data: %d", i);

        /* close file */
        fclose(fp);
	return i;
}


void HandleClient(int sock) 
{
	char recv_buffer[BUFFSIZE];
	char send_buffer[BUFFSIZE];
	char file_buffer[BUFFSIZE];
	int length;
	int received = -1;
        received = 0;        

	received = 0;
	memset(recv_buffer, '\0', BUFFSIZE);
	int bytes = recv (sock, recv_buffer, 2, 0); 
	if (bytes < 0)
	{
		printf ("\nError!!");
		exit(0);
	}
	else
	{
		printf ("\nData received %s", recv_buffer);
		fflush (stdout);
	}


	memset(send_buffer, '\0', BUFFSIZE);
	memset(file_buffer, '\0', BUFFSIZE);

	length = getArray (file_buffer, BUFFSIZE, "/etc/resolv.conf");
	int sent = send (sock, file_buffer, length, 0);
	close(sock);
}

int main(int argc, char *argv[]) 
{
	int serversock, clientsock;
	struct sockaddr_in echoserver, echoclient;

        if (argc != 2) 
	{
		fprintf(stderr, "USAGE: echoserver <port>\n");
		exit(1);
	}
            /* Create the TCP socket */
	if ((serversock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) 
	{
		Die("Failed to create socket");
	}
            /* Construct the server sockaddr_in structure */
	memset(&echoserver, 0, sizeof(echoserver));       /* Clear struct */
	echoserver.sin_family = AF_INET;                  /* Internet/IP */
	echoserver.sin_addr.s_addr = htonl(INADDR_ANY);   /* Incoming addr */
	echoserver.sin_port = htons(atoi(argv[1]));       /* server port */

	/* Bind the server socket */
	if (bind(serversock, (struct sockaddr *) &echoserver, sizeof(echoserver)) < 0) 
	{
		Die("Failed to bind the server socket");
        }
          /* Listen on the server socket */
	if (listen(serversock, MAXPENDING) < 0) 
	{
		Die("Failed to listen on server socket");
	}

/* Run until cancelled */
	while (1) 
	{
		unsigned int clientlen = sizeof(echoclient);
            /* Wait for client connection */
		if ((clientsock = accept(serversock, (struct sockaddr *) &echoclient, &clientlen)) < 0) 
		{
	                Die("Failed to accept client connection");
		}
		fprintf(stdout, "Client connected: %s\n", inet_ntoa(echoclient.sin_addr));
		HandleClient(clientsock);
        }
}

